local lapis = require("lapis")
local db = require("lapis.db")
local jwt = require("luajwt")
local config = require("lapis.config").get()
local jwtTokenKey = config["jwt_key"]
local get_redis = require("lapis.redis").get_redis
-- local Model = require("lapis.db.model").Model

local app = lapis.Application()
-- local UsersModel = Model:extend("users")

app:get("/", function()
    return "Welcome to Lapis " .. require("lapis.version")
end)

-- 登录
app:post("/login", function(self)
    local name = self.params.name
    local pass = self.params.pass

    if name == nil or pass == nil then
        return {
            json = {
                code = 0,
                msg = "参数错误"
            }
        }
    end
    -- return self .param

    -- print(self.param)
    -- local pass = self.params.pass
    -- local info = UsersModel:find()
    local res = db.query("select * from  users where `name` = ?", name)
    if res[1] == nil then
        return {
            json = {
                code = 0,
                msg = "用户不存在"
            }
        }
    end
    res = res[1]
    if res["password"] ~= pass then
        return {
            json = {
                code = 0,
                msg = "密码错误"
            }
        }
    end
    -- 生成token
    local payload = {
        id = res["id"],
        name = res["name"],
        exp = os.time() + 5 * 60 * 60
    }
    local jwttoken = jwt.encode(payload, jwtTokenKey)
    if jwttoken == nil then

        return {
            json = {
                code = 0,
                msg = "生成token失败"
            }
        }
    end
    -- 存入redis

    local redis = get_redis()
    redis:auth("123456")
    -- redis:
    redis:select(5) -- 切换到数据库 5
    local rdres = redis:set("user:info:" .. res["id"], " " .. jwttoken)
    return {
        json = {
            code = 100,
            data = jwttoken,
            msg = "操作成功"
        }
    }
end)

app:post("/info", function(self)
    local token =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoicm9vdCIsImV4cCI6MTczOTkwMDk4N30.DDpRVIzqmQB_KIHdjAhZwfSaGfP9LvXCc4mWqO8KnRI"
    local info, errStr = jwt.decode(token, "", true)
    return {
        json = {
            code = 100,
            info = info,
            err = errStr
        }

    }
end)
return app
